<?php

namespace polymerize\auth\module\login;


use app\common\InstanceTrait;
use app\model\User;
use app\service\WechatService;

class WechatAppGetPhone
{
    use InstanceTrait;

    /**
     * 微信小程序获取手机号
     *
     * @param string $code
     * @param int    $uid
     * @return array
     */
    public function wechatAppGetPhone(string $code, int $uid): array
    {
        try {
            if (!$uid) return ['code' => 400, 'msg' => '用户未登录'];

            $res = WechatService::instance()->wechatAppGetPhone($code);
            if (!isset($res['data']['phone'])) return ['code' => 400, 'msg' => '手机号获取失败'];

            $where1[]  = ['id', '=', $uid];
            $userPhone = User::where($where1)->value('mobile');
            if ($userPhone) {
                if ($userPhone == $res['data']['phone']) {
                    return ['code' => 200, 'msg' => ''];
                }
                return ['code' => 400, 'msg' => '用户手机号已经存在'];
            }
            $data = [
                'mobile'      => $res['data']['phone'],
                'countryCode' => $res['data']['countryCode'] ?? '86',
                'u_time'      => date('Y-m-d H:i:s'),
            ];

            $res = User::updateDataCache($where1, $data);
            if (!$res) return ['code' => 400, 'msg' => '更新数据失败'];

            return ['code' => 200, 'msg' => ''];
        } catch (\Throwable $exception) {
            return ['code' => 400, 'msg' => '绑定手机失败' . $exception->getMessage()];
        }
    }
}
